<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>中国地图点击放大</title>
    <script src="./testEcharts.js"></script>
    <style>
        #marker-box {
            position: absolute;
            left: 0;
            top: 0;
        }

        .marker-tips {
            color: rgb(86, 254, 254);
            font-size: 0.6vw;
            position: absolute;
            width: max-content;
            top: 20px;
        }

        .pulse-box {
            position: relative;
            width: 20px;
            height: 20px;
        }

        .pulse {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(144, 238, 144, 1), rgba(144, 238, 144, 0));
            animation: expandAndFade 4s infinite;
            cursor: pointer;
            transform: scale(0.5);
        }

        .pulse:nth-child(1) {
            animation-delay: 0s;
        }

        .pulse:nth-child(2) {
            animation-delay: 1s;
        }

        .pulse:nth-child(3) {
            animation-delay: 2s;
        }

        .pulse:nth-child(4) {
            animation-delay: 3s;
        }

        @keyframes expandAndFade {
            0% {
                transform: scale(0.5);
                opacity: 1;
            }

            50% {
                transform: scale(1);
                opacity: 0.6;
            }

            100% {
                transform: scale(1.8);
                opacity: 0;
            }
        }

        .img-box {
            width: 120px;
            height: 120px;
            background-color: pink;
        }



        .myImg {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <svg width="0" height="0" >
        <!-- 定义一个路径 -->
        <clipPath id="imgClipPath1">
            <path id="myPath1">
                <!-- 添加路径动画 -->
            </path>
        </clipPath>

    </svg>

    <svg id="valAnimateSvg" width="0" height="0"></svg>


    <div style="width: 1200px; height: 800px; margin: 0 auto;position: relative;">
        <div id="mapContainer" style="width:100%;height:100%"></div>
        <div id="marker-box"></div>
    </div>
    <div id="imgBox" class="img-box">
        <img class="myImg" src="./assets/img/gauge2.png" alt="">
    </div>



    <script>
        let mapData = {}
        const chart = echarts.init(document.getElementById('mapContainer'));
        let currentView = 'china'; // 当前视图层级

        // 初始化全国地图‌:ml-citation{ref="1,3" data="citationList"}
        function initChinaMap() {
            fetch('./utils/map.json')
                .then(response => {
                    if (!response.ok) throw new Error('网络响应异常');
                    return response.json();
                })
                .then(geoJson => {
                    mapData = geoJson
                    echarts.registerMap('china', geoJson); // 注册中国地图数据‌:ml-citation{ref="8" data="citationList"}
                    // const option = {
                    //     series: [{
                    //         type: 'map',
                    //         map: 'china',
                    //         roam: true, // 允许缩放平移‌:ml-citation{ref="2" data="citationList"}
                    //         zoom: 1.2, // 初始缩放级别‌:ml-citation{ref="8" data="citationList"}
                    //         label: { show: true },
                    //         emphasis: { itemStyle: { areaColor: '#ffa022' } } // 高亮颜色‌:ml-citation{ref="2" data="citationList"}
                    //     }]
                    // };
                    chart.setOption({
                        geo: [{
                            map: 'china',
                            roam: false,
                            top: "9%",
                            itemStyle: {
                                shadowBlur: 10,
                                shadowColor: "#013F4C",
                                areaColor: "#013F4C",
                                shadowOffsetX: 0,
                                shadowOffsetY: 8,
                            },
                            regions: [
                                {
                                    // 隐藏南海诸岛,因为顶层已经添加过了
                                    name: "南海诸岛",
                                    itemStyle: {
                                        opacity: 0, // 为 0 时不绘制该图形
                                    },
                                    label: {
                                        show: false,
                                    },
                                },
                            ],

                        }, {
                            map: 'china',
                            top: "8%",
                            roam: false,
                            itemStyle: {
                                normal: {
                                    areaColor: '#005568',
                                    borderColor: '#0BD2DB',  // 边界线颜色  
                                    borderWidth: 2,          // 边界线宽度（默认值）
                                }
                            },

                        }]
                    });
                    bindClickEvent();
                    setMarker()
                })
                .catch(error => console.error('错误详情:', error));


        }

        // 绑定省份点击事件‌:ml-citation{ref="1,4" data="citationList"}
        function bindClickEvent() {
            chart.on('click', async params => {
                document.getElementById('marker-box').innerHTML = ''
                if (params.componentType === 'geo') {
                    const coords = chart.convertFromPixel('geo', [
                        params.event.offsetX,
                        params.event.offsetY
                    ]);
                    console.info(coords)
                    chart.setOption({
                        geo: [{
                            zoom: 3, // 省级视图放大级别‌:ml-citation{ref="8" data="citationList"}
                            center: coords // 聚焦到省份中心‌:ml-citation{ref="4" data="citationList"}
                        }, {
                            zoom: 3, // 省级视图放大级别‌:ml-citation{ref="8" data="citationList"}
                            center: coords // 聚焦到省份中心‌:ml-citation{ref="4" data="citationList"}
                        }]
                    });


                    const provinceName = params.name;
                    const provinceCode = getProvinceCode(provinceName); // 获取省份编码‌:ml-citation{ref="1" data="citationList"}

                    // 动态加载省级GeoJSON数据‌:ml-citation{ref="6" data="citationList"}
                    const res = await fetch(`https://geo.datav.aliyun.com/areas/bound/${provinceCode}_full.json`);
                    const geoJson = await res.json();
                    echarts.registerMap(provinceName, geoJson); // 注册新地图‌:ml-citation{ref="2" data="citationList"}
                    mapData = geoJson

                    setTimeout(() => {
                        chart.setOption({
                            geo: [{
                                map: provinceName,
                                zoom: 1, // 省级视图放大级别‌:ml-citation{ref="8" data="citationList"}
                            }, {
                                map: provinceName,
                                zoom: 1, // 省级视图放大级别‌:ml-citation{ref="8" data="citationList"}
                            }]
                        });
                        const currentCenter = chart.getOption().geo.center
                        chart.setOption({
                            geo: [{
                                center: currentCenter // 聚焦到省份中心‌:ml-citation{ref="4" data="citationList"}
                            }, {
                                center: currentCenter // 聚焦到省份中心‌:ml-citation{ref="4" data="citationList"}
                            }]
                        });

                        setMarker()
                    }, 500)

                    currentView = provinceName;
                }
            });
        }


        function getProvinceCode(name) {
            const find = mapData.features.find((item) => {
                return item.properties.name === name
            })
            return find?.properties.adcode || '';
        }
        function setMarker() {

            // 获取经纬度对应的像素坐标  
            const point = chart.convertToPixel('geo', [102.7494010625, 31.425962749999986]);
            // 创建自定义 HTML 元素  
            const marker = document.createElement('div');
            marker.innerHTML = '<div class="pulse-box"><div class="pulse"></div><div class="pulse"></div><div class="pulse"></div><div class="pulse"></div></div><div class="marker-tips">测试点</div>';  // 自定义 HTML/CSS  
            marker.style.position = 'absolute';
            marker.style.left = `${point[0] - 10}px`;
            marker.style.top = `${point[1] - 10}px`;
            marker.style.cursor = 'pointer';
            marker.style.display = 'flex';
            marker.style.alignItems = 'center';
            marker.style.justifyContent = 'center';
            marker.style.flexDirection = 'column';


            marker.title = 'xxxx'

            // 插入到容器  
            document.getElementById('marker-box').appendChild(marker);

        }
        const pageRadius = 60
        function getSvgPath(rate) {
            // 为每一步生成path
            let animateStr = `M${pageRadius} ${pageRadius} L${pageRadius} 0 A${pageRadius} ${pageRadius} 0 0 1 ${pageRadius} 0 ` //起点
            for (let i = 0; i < 2; i++) {
                let minRate = rate / 2 * (i + 1)
                const { x, y } = getPoint(minRate)
                animateStr += `A${pageRadius} ${pageRadius} 0 0 1 ${x} ${y} `
            }
            animateStr += 'Z;'
            return animateStr
        }
        function getPoint(angleDegrees) {
            // 将角度转换为弧度
            const angleRadians = (angleDegrees - 90) * (Math.PI / 180);

            // 计算终点的x和y坐标
            const endX = pageRadius + pageRadius * Math.cos(angleRadians);
            const endY = pageRadius + pageRadius * Math.sin(angleRadians);

            return { x: endX.toFixed(0), y: endY.toFixed(0) };
        }

        function setAnimate(num) {
            // let k = 20
            // let t=1/k
            // let str = `<animate id="animate0" attributeName="d" dur="${t}s" begin="0" fill="freeze" from="${getSvgPath(1)}" to="${getSvgPath(num / k * 360)}"/> `
            // for (let i = 0; i < k - 1; i++) {

            //     str += `<animate id="animate${i + 1}" attributeName="d" dur="${t}s" begin="animate${i}.end"  fill="freeze" from="${getSvgPath(num / k * (i+1) * 360)}" to="${getSvgPath(num / k * (i + 2) * 360)}"/> `
            // }
            // let dom = document.getElementById('myPath1')
            // dom.innerHTML = str
            // document.getElementById('imgBox').style.clipPath="url(#imgClipPath1)"

            let k = 100
            let t = 1 / k
            let animateStr = ``
            for (let i = 0; i < k; i++) {
                animateStr += getSvgPath(num / k * (i + 1) * 360)
            }
            let dom = document.getElementById('valAnimateSvg')
            let pathId=new Date().getTime()
            let svgHtml = `<defs><clipPath id="${pathId}">`
            svgHtml += `<path>`
            svgHtml += `<animate id="valAnimate" attributeName="d" dur="1s" fill="freeze" values="${animateStr}"></animate>`
            svgHtml += `</path>`
            svgHtml += `</clipPath></defs>`
            dom.innerHTML = svgHtml
            document.getElementById('imgBox').style.clipPath = `url(#${pathId})`
        }

        // 初始化执行
        setAnimate(0.8)
        initChinaMap();
    </script>
</body>

</html>